package com.test.prolenders.activity_prolenders.process_prolenders;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.test.prolenders.R;
import com.test.prolenders.activity_prolenders.ln_prolenders.LnAplyActivity_prolenders;
import com.test.prolenders.base_prolenders.BaseActivity_prolenders;
import com.test.prolenders.base_prolenders.BaseProcessWidgetManager_prolenders;
import com.test.prolenders.bean_prolenders.process_prolenders.ProcessInfo_prolenders;
import com.test.prolenders.bean_prolenders.process_prolenders.ProcessInfo_Data_prolenders;
import com.test.prolenders.bean_prolenders.process_prolenders.ProcessInfo_Step_prolenders;
import com.test.prolenders.bean_prolenders.userinfo_prolenders.AccountList_Fr_prolenders;
import com.test.prolenders.config_prolenders.CountryConfig_prolenders;
import com.test.prolenders.config_prolenders.PermissionConfig_prolenders;
import com.test.prolenders.config_prolenders.ProcessConfig_prolenders;
import com.test.prolenders.dialog_prolenders.BindAccountTipDialog_Fr_prolenders;
import com.test.prolenders.dialog_prolenders.CustomerServiceDialog_prolenders;
import com.test.prolenders.dialog_prolenders.SubmitAccountDialog_Fr_prolenders;
import com.test.prolenders.util_prolenders.UserInfoUtil_prolenders;
import com.test.prolenders.util_prolenders.http_prolenders.HttpUtil_prolenders;
import com.test.prolenders.util_prolenders.image_prolenders.ImageConvert_prolenders;
import com.test.prolenders.view_prolenders.RingProgressBar_prolenders;
import com.test.prolenders.view_prolenders.process_widget_prolenders.AddressPickViewManager_Tanzan_prolenders;
import com.test.prolenders.view_prolenders.process_widget_prolenders.BindAccountViewManager_Fr_prolenders;
import com.test.prolenders.view_prolenders.process_widget_prolenders.DateSelectViewManager_prolenders;
import com.test.prolenders.view_prolenders.process_widget_prolenders.FaceViewManager_prolenders;
import com.test.prolenders.view_prolenders.process_widget_prolenders.GenderSelectViewManager_prolenders;
import com.test.prolenders.view_prolenders.process_widget_prolenders.InputViewManager_prolenders;
import com.test.prolenders.view_prolenders.process_widget_prolenders.OcrViewManager_prolenders;
import com.test.prolenders.view_prolenders.process_widget_prolenders.SelectViewManager_prolenders;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class ProcessActivity_prolenders extends BaseActivity_prolenders implements EasyPermissions.RationaleCallbacks,EasyPermissions.PermissionCallbacks{

    private TextView titleTv,title2Tv,textTv;
    private LinearLayout groupLayout;
    private RingProgressBar_prolenders ringProgressBar;
    private TextView progressTv;
    private View nextBtn;

    private ProcessInfo_Step_prolenders step;

    private final ArrayList<BaseProcessWidgetManager_prolenders> processWidgetManagers = new ArrayList<>();

    private BindAccountViewManager_Fr_prolenders bindAccountViewManager;//法语区绑卡组件
    private OcrViewManager_prolenders ocrViewManager;//Ocr组件
    private FaceViewManager_prolenders faceViewManager;//Face组件

    private String path;

    private Runnable nextBtnRunnable;

    private ActivityResultLauncher<PickVisualMediaRequest> pickMedia;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_process_prolenders);

        page = ProcessInfo_prolenders.getInstance().getStepName(0).toUpperCase();

        titleTv = findViewById(R.id.ap_tv_title);
        title2Tv = findViewById(R.id.ap_tv_title_2);
        textTv = findViewById(R.id.ap_tv_text);

        findViewById(R.id.ap_ib_back).setOnClickListener(v -> onBackPressed());
        findViewById(R.id.ap_ib_customerservice).setOnClickListener(v -> new CustomerServiceDialog_prolenders(this).show());

        ringProgressBar = findViewById(R.id.ap_ringprogressbar);
        progressTv = findViewById(R.id.ap_tv_progress);
        groupLayout = findViewById(R.id.ap_layout_group);
        nextBtn = findViewById(R.id.ap_btn_next);

        step = ProcessInfo_prolenders.getInstance().getStep(0);
        path = step == null ? "":step.getApiUrl();

        initProcess();
    }

    /**
     * 初始化流程
     */
    @SuppressLint("SetTextI18n")
    private void initProcess(){
        if (step == null) {
            onBackPressed();
            return;
        }

        titleTv.setText(step.getTitle());
        title2Tv.setText(step.getTitle());
        textTv.setText(step.getText());

        int percent = ProcessInfo_prolenders.getInstance().getPercent();

        ringProgressBar.setProgress(percent);
        progressTv.setText(percent+"%");

        String stepName = ProcessInfo_prolenders.getInstance().getStepName(0);
        if (!TextUtils.isEmpty(stepName)) page = stepName.toUpperCase();

        //next
        nextBtn.setOnClickListener(v -> {

            HttpUtil_prolenders.getInstance().saveBuriedPoint(page,"SAVE_CLICK","");

            if (step == null||TextUtils.isEmpty(path)) {
                onBackPressed();
                return;
            }

            if (nextBtnRunnable!=null) nextBtnRunnable.run();

        });


        switch (stepName){
            case ProcessConfig_prolenders.Process_Step_Contact:
                initContactProcess();
                break;
            case ProcessConfig_prolenders.Process_Step_Ocr:
                initOcrProcess();
                break;
            case ProcessConfig_prolenders.Process_Step_Sefie:
                initFaceProcess();
                break;
            case ProcessConfig_prolenders.Process_Step_Account:
                if (CountryConfig_prolenders.getInstance().isFrench()){
                    initBindAccountProcess_Fr();
                    HttpUtil_prolenders.getInstance().requestAccountList_Fr(this,this::onFetchFrAccountListResponse);
                    break;
                }
            default:initNormalProcess();
        }

    }

    /**
     * 常规流程
     */
    private void initNormalProcess(){

        for (int i = 0; i< step.getDataListSize(); i++){
            ProcessInfo_Data_prolenders data = step.getProcessData(i);
            if (data==null) continue;
            addInputView(data,null);
        }

        //数据上报处理
        nextBtnRunnable = () -> {

            for (BaseProcessWidgetManager_prolenders processWidgetManager: processWidgetManagers){
                if (!processWidgetManager.checkInput()){
                    Toast.makeText(this,getString(R.string.tips_input_empty_prolenders),Toast.LENGTH_SHORT).show();
                    return;
                }
            }


            TreeMap<String,String> dataMap = new TreeMap<>();

            for (BaseProcessWidgetManager_prolenders baseInfoInputViewManager: processWidgetManagers){

                ProcessInfo_Data_prolenders data = baseInfoInputViewManager.getData();
                if (data==null) continue;

                //地址联动模块
                if (data.getAction().equalsIgnoreCase(ProcessConfig_prolenders.Data_Action_AddressPick)){
                    //坦桑尼亚
                    if (CountryConfig_prolenders.getInstance().isTanzan()){
                        if (!(baseInfoInputViewManager instanceof AddressPickViewManager_Tanzan_prolenders)) continue;
                        AddressPickViewManager_Tanzan_prolenders addressPickTanzanManager = (AddressPickViewManager_Tanzan_prolenders) baseInfoInputViewManager;
                        dataMap.put(data.getParamName(),addressPickTanzanManager.getState());
                        dataMap.put(data.getParamNameCity(),addressPickTanzanManager.getCity());
                    }
                }
                //常规模块
                else dataMap.put(data.getParamName(),baseInfoInputViewManager.getInput());

            }

            HttpUtil_prolenders.getInstance().submitProcessInfo(this,path,dataMap,this::onSubmitInfoResponse);

        };

    }

    /**
     * 联系人流程
     */
    @SuppressLint("InflateParams")
    private void initContactProcess(){

        for (int i = 0; i< step.getExtDataListSize(); i++){
            ProcessInfo_Data_prolenders data = step.getExtProcessData(i);
            if (data==null) continue;
            addInputView(data,null);
        }

        //添加分割线
        if (step.getExtDataListSize()>0) groupLayout.addView(LayoutInflater.from(this).inflate(R.layout.view_line_between_prolenders,null));

        int count = 0;

        while (count< step.getItemCount()){//联系人数量
            for (int i = 0; i< step.getDataListSize(); i++){
                ProcessInfo_Data_prolenders data = step.getProcessData(i);
                if (data==null) continue;
                addInputView(data, step.getRelationShips(count));
            }
            //添加分割线
            if (++count < step.getItemCount()) groupLayout.addView(LayoutInflater.from(this).inflate(R.layout.view_line_between_prolenders,null));
        }

        //数据上报处理
        nextBtnRunnable = () -> {

            TreeMap<String,String> dataMap = new TreeMap<>();

            ArrayList<String> relashipList = new ArrayList<>();
            ArrayList<String> nameList = new ArrayList<>();
            ArrayList<String> phoneList = new ArrayList<>();

            for (BaseProcessWidgetManager_prolenders baseInfoInputViewManager: processWidgetManagers){

                ProcessInfo_Data_prolenders data = baseInfoInputViewManager.getData();
                if (data==null) continue;
                switch (data.getAction()){

                    case ProcessConfig_prolenders.Data_Action_Contact_Relation:
                        relashipList.add(((SelectViewManager_prolenders)baseInfoInputViewManager).getTextInput());
                        break;

                    case ProcessConfig_prolenders.Data_Action_Contact_Name:
                        nameList.add(baseInfoInputViewManager.getInput());
                        break;

                    case ProcessConfig_prolenders.Data_Action_Contact_Phone:
                        phoneList.add(baseInfoInputViewManager.getInput());
                        break;

                    default: dataMap.put(data.getParamName(),baseInfoInputViewManager.getInput());
                }

            }

            //添加联系人信息
            if (!TextUtils.isEmpty(step.getContactParamName())){
                JSONArray jsonArray = new JSONArray();
                for (int i=0;i<relashipList.size();i++){
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("relation",relashipList.get(i));
                        if (i<nameList.size()) jsonObject.put("fullName",nameList.get(i));
                        if (i<phoneList.size()) jsonObject.put("mobile",phoneList.get(i));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    jsonArray.put(jsonObject);
                }
                dataMap.put(step.getContactParamName(),jsonArray.toString());
            }

            HttpUtil_prolenders.getInstance().submitProcessInfo(this,path,dataMap,this::onSubmitInfoResponse);

        };

    }

    /**
     * 法语区绑卡流程
     */
    private void initBindAccountProcess_Fr(){

        @SuppressLint("InflateParams") View bindAccountView = LayoutInflater.from(this).inflate(R.layout.view_process_bindaccount_fr_prolenders,null);
        bindAccountViewManager = new BindAccountViewManager_Fr_prolenders(bindAccountView,null, page);
        groupLayout.addView(bindAccountView);

        nextBtn.setBackgroundResource(R.drawable.bg_blue_gray_rc_24dp_prolenders);

        AccountList_Fr_prolenders.getInstance().setParseRunnable(() -> {
            if (AccountList_Fr_prolenders.getInstance().getBankAccountList().isEmpty())
                nextBtn.setBackgroundResource(R.drawable.bg_blue_gray_rc_24dp_prolenders);
            else
                nextBtn.setBackgroundResource(R.drawable.bg_blue_rc_24dp_prolenders);
        });

        nextBtnRunnable = () -> {

            if (bindAccountView == null) {
                onBackPressed();
                return;
            }

            if (AccountList_Fr_prolenders.getInstance().getBankAccountList().isEmpty()){//无绑卡提示
                Toast.makeText(this,"Veuillez ajouter au moins un compte de réception de prêt valide.",Toast.LENGTH_SHORT).show();
                return;
            }

            if (AccountList_Fr_prolenders.getInstance().getBankAccountList().size()<2){
                new BindAccountTipDialog_Fr_prolenders(this,() -> {
                    new SubmitAccountDialog_Fr_prolenders(this,() ->
                            //提交绑卡
                            HttpUtil_prolenders.getInstance().submitProcessInfo(this,path,new TreeMap<String,String >(){{
                                put("bvn", UserInfoUtil_prolenders.getInstance().getMobile());
                            }},this::onSubmitInfoResponse)
                            ,page).show();
                }).show();
                return;
            }

            new SubmitAccountDialog_Fr_prolenders(this,() ->
                //提交绑卡
                HttpUtil_prolenders.getInstance().submitProcessInfo(this,path,new TreeMap<String,String >(){{
                    put("bvn", UserInfoUtil_prolenders.getInstance().getMobile());
                }},this::onSubmitInfoResponse)
            ,page).show();

        };
    }

    /**
     * 人脸流程
     */
    private void initFaceProcess(){

        @SuppressLint("InflateParams") View faceView = LayoutInflater.from(this).inflate(R.layout.view_process_face_prolenders,null);
        faceViewManager = new FaceViewManager_prolenders(
                faceView,null, page,
                this::onProcessInfoResponse,
                () -> {if (faceViewManager!=null) faceViewManager.onPhotoUploadResponse();}
        );
        groupLayout.addView(faceView);

        nextBtnRunnable = () -> {
            if (faceView==null || faceViewManager==null) {
                onBackPressed();
                return;
            }
            faceViewManager.nextClick(path);
        };
    }

    /**
     * Ocr流程
     */
    private void initOcrProcess(){

        @SuppressLint("InflateParams") View ocrView = LayoutInflater.from(this).inflate(R.layout.view_process_ocr_prolenders,null);
        ocrViewManager = new OcrViewManager_prolenders(
                ocrView,null, page,
                this::onProcessInfoResponse,
                () -> {if (ocrViewManager !=null) ocrViewManager.onPhotoUploadResponse();}
        );
        groupLayout.addView(ocrView);

        pickMedia = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri!=null && ocrViewManager!=null){
                ocrViewManager.photoUri = uri;
                ocrViewManager.imgPath = ImageConvert_prolenders.getBitmapFilePathFromURI(this,ocrViewManager.photoUri);
                ocrViewManager.onPhotoGet();
            }
        });

        ocrViewManager.setPickMedia(pickMedia);

        nextBtnRunnable = () -> {
            if (ocrView == null || ocrViewManager==null) {
                onBackPressed();
                return;
            }
            ocrViewManager.nextClick(path);
        };
    }

    /**
     * 添加信息输入控件
     * @param data 控件参数
     * @param relationships 联系人关系选项，可为空
     */
    @SuppressLint("InflateParams")
    private void addInputView(ProcessInfo_Data_prolenders data, ArrayList<String> relationships){

        View inputView = null;

        switch (data.getAction()){

            case ProcessConfig_prolenders.Data_Action_Select:
                inputView = LayoutInflater.from(this).inflate(R.layout.view_process_select_prolenders,null);
                SelectViewManager_prolenders selectViewManager = new SelectViewManager_prolenders(inputView,data, page);
                processWidgetManagers.add(selectViewManager);
                break;

            case ProcessConfig_prolenders.Data_Action_DatePick:
                inputView = LayoutInflater.from(this).inflate(R.layout.view_process_dateselect_prolenders,null);
                DateSelectViewManager_prolenders datePickWidgetsManager = new DateSelectViewManager_prolenders(inputView,data, page);
                processWidgetManagers.add(datePickWidgetsManager);
                break;

            case ProcessConfig_prolenders.Data_Action_Contact_Relation://联系人-关系
                if (relationships!=null) data.setRelationships(relationships);
                inputView = LayoutInflater.from(this).inflate(R.layout.view_process_select_prolenders,null);
                SelectViewManager_prolenders contactSelectViewManager = new SelectViewManager_prolenders(inputView,data, page);
                processWidgetManagers.add(contactSelectViewManager);
                break;

            case ProcessConfig_prolenders.Data_Action_GenderPick:
                inputView = LayoutInflater.from(this).inflate(R.layout.view_process_genderselect_prolenders,null);
                GenderSelectViewManager_prolenders genderSelectViewManager = new GenderSelectViewManager_prolenders(inputView,data, page);
                processWidgetManagers.add(genderSelectViewManager);
                break;

            case ProcessConfig_prolenders.Data_Action_AddressPick://地址联动模块
                //坦桑尼亚
                if (CountryConfig_prolenders.getInstance().isTanzan()){
                    inputView = LayoutInflater.from(this).inflate(R.layout.view_process_select_prolenders,null);
                    AddressPickViewManager_Tanzan_prolenders addressPickViewManagerTanzan = new AddressPickViewManager_Tanzan_prolenders(inputView,data, page);
                    processWidgetManagers.add(addressPickViewManagerTanzan);
                }
                break;

            case ProcessConfig_prolenders.Data_Action_Input:
            case ProcessConfig_prolenders.Data_Action_Contact_Name://联系人-名字
            case ProcessConfig_prolenders.Data_Action_Contact_Phone://联系人-电话
            default:
                inputView = LayoutInflater.from(this).inflate(R.layout.view_process_input_prolenders,null);
                InputViewManager_prolenders inputWidgetsManager = new InputViewManager_prolenders(inputView,data, page);
                processWidgetManagers.add(inputWidgetsManager);
                break;
        }

        if (inputView!=null) groupLayout.addView(inputView);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {}

    @Override
    public void onRationaleDenied(int requestCode) {}

    @Override
    public void onRationaleAccepted(int requestCode) {
        if (requestCode == PermissionConfig_prolenders.PermissionCode_Camera)
            EasyPermissions.requestPermissions(this,
                    getString(R.string.launch_permissions_camera_prolenders),
                    PermissionConfig_prolenders.PermissionCode_Camera,
                    Manifest.permission.CAMERA);
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (requestCode == PermissionConfig_prolenders.PermissionCode_Camera) {
            if (EasyPermissions.somePermissionPermanentlyDenied(this, perms))
                new AppSettingsDialog.Builder(this).build().show();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @AfterPermissionGranted(PermissionConfig_prolenders.PermissionCode_Camera)
    public void onCameraPermissionAgree() {
        if (faceViewManager != null) faceViewManager.onCameraPermissionAgree();
        else if (ocrViewManager!=null) ocrViewManager.onCameraPermissionAgree();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (ocrViewManager!=null && requestCode== OcrViewManager_prolenders.Flag_StartCamera){
            ocrViewManager.onPhotoGet();
        }
    }

    //-------------------------------------------响应-----------------------------------------------------------

    //信息上报成功响应
    public void onSubmitInfoResponse(){
        HttpUtil_prolenders.getInstance().userProcess(this,this::onProcessInfoResponse);
    }

    public void onFetchFrAccountListResponse(){
        if (bindAccountViewManager!=null) bindAccountViewManager.refreshAccountList();
    }

    public void onProcessInfoResponse(){
        //无流程：跳转到申请页
        if (ProcessInfo_prolenders.getInstance().getSteps().isEmpty())
            startActivity(new Intent(this, LnAplyActivity_prolenders.class));
            //有流程：跳转到流程页
        else startActivity(new Intent(this, ProcessActivity_prolenders.class));

        finish();
    }

}